package com.certification.service.impl;

import com.certification.common.utils.TimeUtils;
import com.certification.entity.CertAttachment;
import com.certification.entity.Certification;
import com.certification.entity.ProfessionSelfEvaluation;
import com.certification.entity.SchoolInvestigate;
import com.certification.mapper.CertAttachmentMapper;
import com.certification.service.*;
import com.certification.vo.CorrectImproveAdminVO;
import com.certification.vo.ResponseMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Objects;

import static com.certification.constants.CertConstant.*;


/**
 * @author copa
 * @createDate 2022-03-31 16:39
 * @function
 */
@Service
public class CertAttachmentServiceImpl implements CertAttachmentService {

    @Resource
    private CertAttachmentMapper certAttachmentMapper;

    @Resource
    private CertificationService certificationService;

    @Resource
    private ProfessionSelfEvaluationService professionSelfEvaluationService;

    @Resource
    private SchoolInvestigateService schoolInvestigateService;

    @Resource
    private CorrectImproveService correctImproveService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<Integer> upload(MultipartFile multiFile, HttpSession session) {
        String originalFilename = multiFile.getOriginalFilename();
        if (!(originalFilename.endsWith(".doc")
                || originalFilename.endsWith(".docx")
                || originalFilename.endsWith(".pdf")
                || originalFilename.endsWith(".xls")
                || originalFilename.endsWith(".xlsx"))) {
            return ResponseMessage.errorMsg("请上传带有.doc、.docx、.xls、.xlsx或.pdf的文件~");
        }
        ServletContext servletContext = session.getServletContext();
        String uploadPath = servletContext.getRealPath("upload");
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdir();
        }
        String fileName = TimeUtils.fileTimeName() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        String finalPath = uploadPath + File.separator + fileName;
        try {
            multiFile.transferTo(new File(finalPath));
            CertAttachment certAttachment = new CertAttachment();
            certAttachment.setPath(finalPath)
                    .setOriginName(originalFilename);
            int insert = certAttachmentMapper.insert(certAttachment);
            if (insert > 0) {
                return ResponseMessage.success(certAttachment.getId());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
    }

    @Override
    public ResponseMessage<CertAttachment> getFileInfo(Integer certStage, Integer attachmentId, Integer userId) {
        Certification cert = certificationService.getOneCertByCertStageAndPrincipalId(certStage, userId, null, null);
        if (Objects.isNull(cert)) {
            return ResponseMessage.errorMsg("没有查到该数据啦~");
        }
        return getCertAttachment(certStage, cert, attachmentId);
    }

    @Override
    public ResponseEntity<byte[]> fileDownload(Integer certStage, Integer attachmentId, Integer userId, HttpSession session) {
        ResponseMessage<CertAttachment> certAttachmentResponseMessage = getFileInfo(certStage, attachmentId, userId);
        ResponseEntity<byte[]> responseEntity = null;
        if (certAttachmentResponseMessage.isNotSuccess()) {
            HttpStatus statusCode = HttpStatus.NOT_FOUND;
            responseEntity = new ResponseEntity("没有找到该文件~", null, statusCode);
            return responseEntity;
        }
        String realPath = certAttachmentResponseMessage.getData().getPath();
        //创建输入流
        InputStream is = null;
        try {
            is = new FileInputStream(realPath);
            //创建字节数组
            byte[] bytes = new byte[is.available()];
            //将流读到字节数组中
            is.read(bytes);
            //创建HttpHeaders对象设置响应头信息
            MultiValueMap<String, String> headers = new HttpHeaders();
            //设置要下载方式以及下载文件的名字
            realPath = realPath.substring(realPath.lastIndexOf(File.separator));
            headers.add("Content-Disposition", "attachment;filename=" + realPath.substring(1));
            //设置响应状态码
            HttpStatus statusCode = HttpStatus.OK;
            //创建ResponseEntity对象
            responseEntity = new ResponseEntity<>(bytes, headers, statusCode);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭输入流
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    @Override
    public ResponseEntity<byte[]> fileDownloadAdmin(Integer attachmentId, HttpSession session) {
        CertAttachment certAttachment = certAttachmentMapper.selectById(attachmentId);
        ResponseEntity<byte[]> responseEntity = null;
        if (Objects.isNull(certAttachment)) {
            HttpStatus statusCode = HttpStatus.NOT_FOUND;
            responseEntity = new ResponseEntity("没有找到该文件~", null, statusCode);
            return responseEntity;
        }
        String realPath = certAttachment.getPath();
        //String originPath = certAttachment.getOriginName();

        //创建输入流
        InputStream is = null;
        try {
            is = new FileInputStream(realPath);
            //创建字节数组
            byte[] bytes = new byte[is.available()];
            //将流读到字节数组中
            is.read(bytes);
            //创建HttpHeaders对象设置响应头信息
            MultiValueMap<String, String> headers = new HttpHeaders();
            //设置要下载方式以及下载文件的名字
            //headers.add("Content-Disposition", "attachment;filename=" +  java.net.URLEncoder.encode(originPath, "UTF-8"));
            realPath = realPath.substring(realPath.lastIndexOf(File.separator));
            headers.add("Content-Disposition", "attachment;filename=" + realPath.substring(1));
            //设置响应状态码
            HttpStatus statusCode = HttpStatus.OK;
            //创建ResponseEntity对象
            responseEntity = new ResponseEntity<>(bytes, headers, statusCode);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭输入流
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<Integer> uploadFile(String url) {
        CertAttachment certAttachment = new CertAttachment().setPath(url);
        int insert = certAttachmentMapper.insert(certAttachment);
        if (insert > 0) {
            return ResponseMessage.success(certAttachment.getId());
        }
        return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
    }

    @Override
    public ResponseMessage<CertAttachment> getFileInfoAdmin(Integer attachmentId) {
        return ResponseMessage.success(certAttachmentMapper.selectById(attachmentId));
    }

    private ResponseMessage<CertAttachment> getCertAttachment(Integer certStage, Certification cert, Integer attachmentId) {
        CertAttachment certAttachment = null;

//        switch (certStage) {
//            case CERTIFICATION:
//                if (Objects.equals(attachmentId, cert.getCertAttachmentId())) {
//                    certAttachment = certAttachmentMapper.selectById(attachmentId);
//                }
//                break;
//            case PROFESSION_SELF_EVALUATION:
//                ResponseMessage<ProfessionSelfEvaluation> proResponseMessage = professionSelfEvaluationService.getProDetailByCertId(cert.getId());
//                if (proResponseMessage.isNotSuccess()) {
//                    return ResponseMessage.errorMsg("没有查到任何记录~");
//                }
//                if (Objects.equals(attachmentId, proResponseMessage.getData().getCertAttachmentId())) {
//                    certAttachment = certAttachmentMapper.selectById(attachmentId);
//                }
//                break;
//            case SCHOOL_INVESTIGATE:
//                ResponseMessage<SchoolInvestigate> investResponseMessage = schoolInvestigateService.getInvestDetailAdmin(cert.getId(), null);
//                if (investResponseMessage.isNotSuccess()) {
//                    return ResponseMessage.errorMsg("没有查到任何记录~");
//                }
//                if (Objects.equals(attachmentId, investResponseMessage.getData().getCertAttachmentId())) {
//                    certAttachment = certAttachmentMapper.selectById(attachmentId);
//                }
//                break;
//            case CORRECT_IMPROVE:
//                ResponseMessage<CorrectImproveAdminVO> correctImproveResponseMessage = correctImproveService.getImproveDetailAdmin(cert.getId());
//                if (correctImproveResponseMessage.isNotSuccess()) {
//                    return ResponseMessage.errorMsg("没有查到任何记录~");
//                }
//                if (Objects.equals(attachmentId, correctImproveResponseMessage.getData().getCorrectImprove().getCertAttachmentId())) {
//                    certAttachment = certAttachmentMapper.selectById(attachmentId);
//                }
//                break;
//            default:
//                return ResponseMessage.errorMsg("没有查到任何记录~");
//        }
        return ResponseMessage.success(certAttachment);
    }
}
